<?php
/**
 * Created by laoyu.
 * User: hilaoyu@qq.com
 * Date: 2018/5/22
 * Time: 17:11
 */

namespace Hilaoyu\LaravelExtend\Providers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class DebugSqlServiceProvider extends ServiceProvider
{
    public function boot()
    {


    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        \Illuminate\Database\Query\Builder::macro('toRawSql', function(){
            return array_reduce($this->getBindings(), function($sql, $binding){
                if ($binding instanceof \DateTime) {
                    $binding = $binding->format('\'Y-m-d H:i:s\'');
                }
                return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
            }, $this->toSql());
        });

        \Illuminate\Database\Eloquent\Builder::macro('toRawSql', function(){
            return ($this->getQuery()->toRawSql());
        });


        if(!config('app.debug',false)){
            return ;
        }

        DB::listen(function ($query) {

            //\Illuminate\Database\Events\QueryExecuted::class;
            $sql =  array_reduce($query->bindings, function($sql, $binding){
                if ($binding instanceof \DateTime) {
                    $binding = $binding->format('\'Y-m-d H:i:s\'');
                }
                return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'" , $sql, 1);
            }, $query->sql);



            comDebug($sql);

        });
    }
}
